import 'package:flutter/material.dart';

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

//自定义组件
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // MaterialApp是根组件
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Dialog Web'),
          ),
          body: WebRequestDemo()),
      theme: ThemeData(primaryColor: Colors.blue),
    );
  }
}

class WebRequestDemo extends StatefulWidget {
  WebRequestDemo({Key? key}) : super(key: key);

  @override
  _WebRequestDemoState createState() => _WebRequestDemoState();
}

class _WebRequestDemoState extends State<WebRequestDemo> {
  late List result;
  _getDate() async {
    var url = Uri.parse('http://localhost:8080/address');
    print(url);
    var response = await http.get(url);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body) as List<dynamic>;
      result = jsonResponse;
      print(' $jsonResponse.');
    } else {
      print(
          'Request failed with status: ${response.statusCode}. ${response.statusCode}');
    }
  }

  _postDate() async {
    var url = Uri.parse('http://localhost:8080/add/goods');
    final jsonString = """
        {
          "persons" : [
            {
              "name" : "Joe",
              "age" : 12
            }
          ]
        }
        """;
    var response = await http.post(url,
        body: jsonString,
        headers: {"Content-Type": "application/json;charset=utf-8"});

    if (response.statusCode == 200) {
      //把JSON字符串转换成对象
      var jsonResponse = convert.jsonDecode(response.body);

      print(' $jsonResponse.');
    } else {
      print(
          'Request failed with status: ${response.statusCode}. ${response.statusCode}');
    }
  }

  @override
  void initState() {
    super.initState();
    _getDate();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(onPressed: _getDate, child: Text('Get Req')),
          ElevatedButton(onPressed: _postDate, child: Text('Post Req'))
        ],
      ),
    );
  }
}
